package com.auction.service.impl;

import com.auction.common.dao.MyBaseServiceImpl;
import com.auction.entity.TransactionLog;
import com.auction.entity.Wallet;
import com.auction.mapper.TransactionLogMapper;
import com.auction.mapper.WalletMapper;
import com.auction.service.WalletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

import static com.auction.common.utils.Assert.isSuccess;

@Service
public class WalletServiceImpl extends MyBaseServiceImpl<Wallet, WalletMapper> implements WalletService {


    @Autowired
    private TransactionLogMapper transactionLogMapper;

    @Override
    @Transactional
    public int updateWallet(TransactionLog transactionLog) {

        //添加流水记录
        int res = transactionLogMapper.insert(transactionLog);
        isSuccess(res,"更新流水失败");

        //判断是否有流水类型，没有报错
        if (transactionLog.getTransaction_type()==0)
            isSuccess(0,"数据异常");

        //判断流水是支出还是增加
        //支出就将金额变为负数
        if(transactionLog.getTransaction_type()<0)
            transactionLog.setAmount(transactionLog.getAmount()*-1);

        //更新钱包余额
        res = baseMapper.updateAmount(transactionLog);
        isSuccess(res,"更余额失败");
        return 1;
    }

    @Override
    @Transactional
    public Map getWalletByUserId(int user_id) {
        Map info = baseMapper.getWalletByUserId(user_id);

        //该用户未用有账户
        if (null == info){
            //给该用户添加账户

            Wallet wallet = new Wallet();
            wallet.setUser_id(user_id);
            wallet.setBalance(0);
            int rs = baseMapper.insert(wallet);
            isSuccess(rs,"账户创建失败");

            //添加账户成功后在查一次
            info = baseMapper.getWalletByUserId(user_id);
        } else
             info=baseMapper.getWalletByUserId(user_id);

        return info;
    }
}
